package com.itheima.tlias.tliasweb.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
public class CookieController {

    @GetMapping("c1")
    public String createCookie(HttpServletResponse response){
        // 登陆成功之后，把生成cookie，把用户id和用户名写入到cookie下发给浏览器
        // 创建cookie
        Cookie cookie = new Cookie("username", "zhangsan");
        // 添加到响应头
        response.addCookie(cookie);
        Cookie cookie2 = new Cookie("age", "18");
        response.addCookie(cookie2);

        Cookie cookie3 = new Cookie("id", "121212");
        response.addCookie(cookie3);

        log.info("执行业务逻辑");

        System.out.println(1/0);

        return "success";
    }

    @GetMapping("c2")    // @CookieValue根据名称读取cookie的值
    public String getCookie(@CookieValue("username")String username,
                            @CookieValue("age")Integer age,
                            HttpServletRequest request){

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            log.info("---------->"+cookie.getName());
        }

        // 浏览器下次请求的时候，会自动上传当前域下的cookie
        return username + ":" + age;
    }

}
